import { API, APIURL as HOST, CRStatus, PostInfo } from '../api'
import { DateLike, convertTime } from '../utils'

/** 获取链接 */
export const getLink =
	async (url: string) => (await API.getLink([['url', 0, url, 0]]))[1]

/** 获取帖子 */
export const getPost = async (pid: number) => (await API.getPost([pid]))[0]

/**
 * 根据状态获取变更请求数量
 * @param pid 帖子ID
 * @param status 状态
 */
export async function countCRByStatus(pid: number, status: CRStatus) {
	const [count] = await API.getCR([['', -1, `pid=${pid} and status=${status}`, 0]], void 0, 0, 0)
	return count
}

/**
 * 获取指定时间前最后一个变更请求
 * @param pid 帖子ID
 * @param status 状态
 */
export async function getLastCR(pid: number, status: CRStatus, end: DateLike = new Date) {
	end = convertTime(end)
	const [, cr] = await API.getCR([['', -1, `pid=${pid} and status=${status
	} and created_at<=${end}`, 0]], void 0, 0, 1)
	return cr
}

/**
 * 获取指定时间段内的帖子锁定次数
 * @param pid 帖子ID
 * @param start 开始时间
 * @param end 结束时间
 * @returns 锁定次数
 */
export async function countLockedPost(pid: number, start: DateLike, end: DateLike = new Date) {
	start = convertTime(start)
	end = convertTime(end)
	const [count] = await API.getLockedPost([['', -1, `pid=${pid} and ${start
	}<=created_at and created_at<=${end} or ${start}<=updated_at and updated_at<=${end}`, 0]], void 0, 0, 0)
	return count
}

export async function updateImg(img: HTMLImageElement, post: PostInfo, full = false) {
	img.alt = img.title = post.tags
	let i = 0
	// fallback
	const onError = (e: ErrorEvent) => {
		// TODO 网络未连接时不处理
		if (e.error?.message)
			// 反馈链接失效
			requestIdleCallback(() => API.setLink(links[i], 1))
		i++
		if (i >= links.length)
			img.classList.add('error')
		else
			img.src = parseURL(links[i], full)
	}
	img.addEventListener('load',
		() => img.removeEventListener('error', onError), {
		once: true
	})
	img.addEventListener('error', onError)
	var links = await API.linksOf(post.hash)
	img.src = parseURL(links[i], full)
}

function parseURL(url: string, full = false) {
	if (url.startsWith('file://')) {
		url = `//${HOST}/thumb/${encodeURI(url).replace(/#/g, '%23')}/`
		if (!full)
			url += '192x108.webp'
	}
	return url
}
